using System;
using System.Linq;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Wordprocessing;

namespace MailMerge.Infrastructure
{
	public class ContentControlInfo
	{
		public OpenXmlElement Self { get; set; }
		public OpenXmlCompositeElement Content { get; set; }
		public SdtProperties Properties { get; set; }

		public ContentControlInfo(OpenXmlElement structuredDocumentTag)
		{
			Properties = structuredDocumentTag.GetFirstChild<SdtProperties>();
			if (Properties == null) throw new InvalidOperationException("Not a content control. No Properties element.");

			Self = structuredDocumentTag;

			Content = (OpenXmlCompositeElement)structuredDocumentTag.Elements().LastOrDefault();
		}

		public string Title
		{
			get
			{
				var title =
					Properties
						.GetFirstChild<SdtAlias>();

				return 
					title != null && title.Val.HasValue 
					? title.Val.Value 
					: null;
			}
		}

		public string Tag
		{
			get
			{
				var tag = 
					Properties
						.GetFirstChild<Tag>();

				return 
					tag != null && tag.Val.HasValue 
					? tag.Val.Value 
					: null;
			}
		}
		

		public virtual void OverwriteText(string text)
		{
			// Note: this is a naive implementation 
			var columnText = Content.Descendants<Text>().FirstOrDefault();
			if (columnText != null) columnText.Text = text;
			return;

			//Note: production implementation has to take into account context. E.g.

			//var paras = Content.Descendants<Paragraph>().ToList();

			//if (paras.Count() == 0)
			//{
				//If we're lucky this is just a simple paragraph
				//var columnText = Content.Descendants<Text>().FirstOrDefault();
				//if (columnText != null) columnText.Text = text;
				//return;
//			}

			//if not we have probably encountered some more structured content
			//var firstParagraph = paras.First().CloneNode(true);
			//foreach (var para in paras)
			//    para.Remove();

			//firstParagraph.RemoveAllChildren();

			//OpenXmlElement root = null;

			//root = 
			//    Content.GetType() == typeof(SdtContentCell) 
			//    ? Content.GetFirstChild<TableCell>() 
			//    : Content;

			//root
			//   .AppendChild(firstParagraph)
			//       .AppendChild(new Run())
			//           .AppendChild(new Text() { Text = text });
		}
	}
}